﻿using Exiled.API.Features;
using RgCore.Database;
using RgCore.GameData;
using RgCore.Modules;
using RgCore.PlayerHud;
using System.Collections.Generic;
using System.Linq;

namespace OfflineMessage
{
    public class OfflineMessage : RgPlugin
    {
        public override string Name => "离线消息";

        public override string Id => "offline_message";

        public override void OnDisabled()
        {
            if (DatabaseController.DatabaseDisabled)
            {
                return;
            }
            GameplayData.OnInitializedData -= GameplayData_OnInitializedData;
        }

        public override void OnEnabled()
        {
            if (DatabaseController.DatabaseDisabled)
            {
                Log.Warn("由于数据库未启用，此插件不加载");
                return;
            }
            GameplayData.OnInitializedData += GameplayData_OnInitializedData;
        }

        private async void GameplayData_OnInitializedData(Exiled.API.Features.Player player)
        {
            if (DatabaseController.DatabaseDisabled)
            {
                return;
            }
            var filter = new Dictionary<string, object> { { "userid", player.UserId } };
            QueryCommandRequest cmd = new QueryCommandRequest("cdcp_offline_message", filter, false, "message");
            var list = (await cmd.GetResponseResult()).FirstOrDefault();
            if (list == null)
                return;
            string msg = list["message"].ToString();
            player.SendRawMsg("", $"<color=#00FFFF>[来自技术组给你的留言信息]</color>\n{msg}", 20, ScreenLocation.Center, false);
            NoResponseCommandRequest cmd2 = new NoResponseCommandRequest("cdcp_offline_message", RequestType.Delete, null, filter);
            await cmd2.ProcessNonQuery();
        }
    }
}